package com.nancy.java_design.proxy.demo3;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * CGLIB动态代理
 * 目标对象没有实现接口
 */
public class CGLIBProxyFactory implements MethodInterceptor {
    private TranStation tranStation = new TranStation();

    // 获取代理对象
    public TranStation getProxyInstance() {
        // 创建Enhancer对象，设置父类
        Enhancer enhancer = new Enhancer();
        // 设置父类
        enhancer.setSuperclass(tranStation.getClass());
        // 设置回调函数
        enhancer.setCallback(this);
        // 创建代理对象
        TranStation proxyObject = (TranStation) enhancer.create();

        return proxyObject;
    }

    @Override
    public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
        //代理方式，自己要做的事情
        System.out.println("代售点收取一定的代理服务费(CGLIB动态代理)");
        // 执行目标方法
        Object object = method.invoke(tranStation, args);
        return object;
    }
}
